package com.sh.shanhuo.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Patterns;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.king.zxing.CameraScan;
import com.king.zxing.DecodeConfig;
import com.king.zxing.DecodeFormatManager;
import com.king.zxing.DefaultCameraScan;
import com.king.zxing.analyze.MultiFormatAnalyzer;
import com.sh.shanhuo.R;
import com.sh.shanhuo.activity.MainActivity;
import com.sh.shanhuo.adapter.EditSortAdapter;
import com.sh.shanhuo.bean.AddSiteBean;
import com.sh.shanhuo.bean.LoginBean;
import com.sh.shanhuo.database.sort.SortInfoEntity;
import com.sh.shanhuo.database.web.WebInfoDBUtils;
import com.sh.shanhuo.database.web.WebInfoEntity;
import com.sh.shanhuo.filter.TextInputFilter;
import com.sh.shanhuo.listener.AddSiteResultCallback;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.listener.SimpleResultCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.Tools;
import com.sh.shanhuo.view.CommonItemDecoration;
import com.tencent.mmkv.MMKV;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.camera.view.PreviewView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.Call;

public class CommonEditDialog {

    public static void loginDialog(Activity activity, String acc, String pwd, SimpleResultCallback resultCallback) {
        MMKV mmkv = MMKV.defaultMMKV();
        if (mmkv == null) {
            return;
        }
        Dialog dialog = new Dialog(activity, R.style.no_title);
        View view = View.inflate(activity, R.layout.dialog_edit, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = (int) (Tools.getScreenWidth(activity) * 0.85);
        dialogWindow.setAttributes(lp);

        EditText account = view.findViewById(R.id.account);
        EditText password = view.findViewById(R.id.password);
        account.setText(acc);
        password.setText(pwd);

        TextView forgetPassword = view.findViewById(R.id.forgetPassword);
        CheckBox savePassword = view.findViewById(R.id.savePassword);
        TextView gotoRegister = view.findViewById(R.id.gotoRegister);
        TextView login = view.findViewById(R.id.login);
        TextView accountLine = view.findViewById(R.id.accountLine);
        TextView accountError = view.findViewById(R.id.accountError);
        TextView passwordLine = view.findViewById(R.id.passwordLine);
        TextView passwordError = view.findViewById(R.id.passwordError);
        gotoRegister.setText(Html.fromHtml("没有账号？" + "<font color='#007AFF'>" + "马上注册" + "</font>"));
        if (!activity.isFinishing()) {
            dialog.show();
        }
        savePassword.setChecked(mmkv.decodeBool("save_password"));

        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                passwordLine.setBackgroundColor(activity.getResources().getColor(R.color.lines, null));
                passwordError.setVisibility(View.GONE);
            }
        });

        String regular = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_";
        //noinspection deprecation
        account.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                return regular.toCharArray();
            }
        });
        login.setOnClickListener(v -> {
            if (savePassword.isChecked()) {
                mmkv.encode("account", account.getText().toString().trim());
                mmkv.encode("password", password.getText().toString().trim());
            } else {
                mmkv.encode("account", account.getText().toString().trim());
            }
            mmkv.encode("save_password", savePassword.isChecked());
            Map<String, String> params = new HashMap<>();
            params.put("userName", account.getText().toString().trim());
            params.put("password", password.getText().toString().trim());
            OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.LOGIN, params, new GsonObjectCallback<LoginBean>() {
                @Override
                public void onUi(LoginBean bean) {
                    if (bean == null) {
                        Toast.makeText(activity, "登录失败", Toast.LENGTH_SHORT).show();
                        mmkv.encode("isLogin", false);
                        return;
                    }
                    if (bean.getMsg().contains("密码错误")) {
                        passwordLine.setBackgroundColor(activity.getResources().getColor(R.color.error, null));
                        passwordError.setVisibility(View.VISIBLE);
                        return;
                    }
                    if (bean.getCode() == 200 && "操作成功".equals(bean.getMsg())) {
                        dialog.dismiss();
                        mmkv.encode("isLogin", true);
                        if (resultCallback != null) {
                            resultCallback.onBean(bean);
                        }
                    } else {
                        mmkv.encode("isLogin", false);
                        Toast.makeText(activity, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailed(Call call, IOException e) {
                    Toast.makeText(activity, "登录失败", Toast.LENGTH_SHORT).show();
                    mmkv.encode("isLogin", false);
                }
            });
        });
        forgetPassword.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("forgetPassword");
            }
        });

        gotoRegister.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("gotoRegister");
            }
        });
        dialog.setOnDismissListener(DialogInterface::dismiss);
    }

    public static void registerDialog(Activity activity, SimpleResultCallback resultCallback) {
        Dialog dialog = new Dialog(activity, R.style.no_title);
        View view = View.inflate(activity, R.layout.dialog_register, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = (int) (Tools.getScreenWidth(activity) * 0.85);
        dialogWindow.setAttributes(lp);

        EditText account = view.findViewById(R.id.account);
        EditText password = view.findViewById(R.id.password);
        EditText confirmPassword = view.findViewById(R.id.confirmPassword);
        TextView register = view.findViewById(R.id.register);
        TextView gotoLogin = view.findViewById(R.id.gotoLogin);
        TextView passwordError = view.findViewById(R.id.passwordError);
        TextView confirmPasswordError = view.findViewById(R.id.confirmPasswordError);
        gotoLogin.setText(Html.fromHtml("已有账号？" + "<font color='#007AFF'>" + "马上登录" + "</font>"));
        if (!activity.isFinishing()) {
            dialog.show();
        }

        String regular = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_";
        //noinspection deprecation
        account.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                return regular.toCharArray();
            }
        });

        password.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                passwordError.setVisibility(View.GONE);
                if (password.getText().toString().length() < 6) {
                    passwordError.setVisibility(View.VISIBLE);
                    passwordError.setText("密码不可少于6位");
                }
                if (password.getText().toString().contains(" ")) {
                    passwordError.setVisibility(View.VISIBLE);
                    passwordError.setText("密码不可包含空格");
                }
            }
        });

        confirmPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                confirmPasswordError.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        register.setOnClickListener(v -> {
            if (account.getText().toString().trim().isEmpty()) {
                Toast.makeText(activity, "账号不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.getText().toString().trim().isEmpty()) {
                Toast.makeText(activity, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if (confirmPassword.getText().toString().trim().isEmpty()) {
                Toast.makeText(activity, "确认密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.getText().toString().trim().length() < 6) {
                Toast.makeText(activity, "密码不能少于6位", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!password.getText().toString().trim().equals(confirmPassword.getText().toString().trim())) {
                confirmPasswordError.setVisibility(View.VISIBLE);
                confirmPasswordError.setText("密码输入不一致！");
                return;
            }
            if (resultCallback != null) {
                resultCallback.onResult(account.getText().toString().trim(), password.getText().toString().trim());
            }
            dialog.dismiss();
        });
        gotoLogin.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("gotoLogin");
            }
        });
        dialog.setOnDismissListener(DialogInterface::dismiss);
    }

    public static void scanDialog(MainActivity activity, SimpleResultCallback resultCallback) {
        Dialog dialog = new Dialog(activity, R.style.no_title);
        View view = View.inflate(activity, R.layout.dialog_scan, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = (int) (Tools.getScreenWidth(activity) * 0.85);
        dialogWindow.setAttributes(lp);

        TextView cancel = view.findViewById(R.id.cancel);
        PreviewView previewView = view.findViewById(R.id.previewView);
        cancel.setOnClickListener(v -> dialog.dismiss());
        DecodeConfig decodeConfig = new DecodeConfig();
        decodeConfig.setHints(DecodeFormatManager.QR_CODE_HINTS)
                .setFullAreaScan(false)
                .setAreaRectRatio(0.8f)
                .setAreaRectVerticalOffset(0)
                .setAreaRectHorizontalOffset(0);
        CameraScan mCameraScan = new DefaultCameraScan(activity, previewView);
        mCameraScan.setOnScanResultCallback(result -> {
            resultCallback.onResult(result.getText(), "");
            dialog.dismiss();
            return true;
        });
        mCameraScan.startCamera();
        mCameraScan.setVibrate(false)
                .setAnalyzer(new MultiFormatAnalyzer(decodeConfig));
        dialog.setOnDismissListener(dialog1 -> {
            dialog1.dismiss();
            mCameraScan.release();
        });
        dialog.show();
    }

    public static void scanResultDialog(Activity activity, String webSite, String webName,
                                        String webIntroduce, String appUserId, String appUserNickName, AddSiteResultCallback resultCallback) {
        Dialog dialog = new Dialog(activity, R.style.no_title);
        View view = View.inflate(activity, R.layout.dialog_scan_result, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
        lp.width = Tools.getScreenWidth(activity);
        dialogWindow.setAttributes(lp);

        EditText website = view.findViewById(R.id.website);
        EditText name = view.findViewById(R.id.name);
        EditText description = view.findViewById(R.id.description);
        name.setFilters(new InputFilter[]{new TextInputFilter(true, 10, activity)});
        description.setFilters(new InputFilter[]{new TextInputFilter(true, 30, activity)});
        TextView confirm = view.findViewById(R.id.confirm);
        TextView cancel = view.findViewById(R.id.cancel);
        if (!activity.isFinishing()) {
            dialog.show();
        }
        final AddSiteBean.DataBean[] dataBean = {null};
        SimpleResultCallback callback = new SimpleResultCallback() {
            @Override
            public void onResult(String data1, String data2) {

            }

            @Override
            public void onButton(String action) {

            }

            @Override
            public void onBean(Object obj) {
                if (obj == null){
                    dataBean[0] = null;
                    name.setEnabled(true);
                    description.setEnabled(true);
                } else {
                    dataBean[0] = (AddSiteBean.DataBean)obj;
                    name.setText(dataBean[0].getWebName());
                    description.setText((String) dataBean[0].getIntroduce());
                    name.setEnabled(false);
                    description.setEnabled(false);
                }
            }
        };
        if (TextUtils.isEmpty(webSite)) {
            website.setText(new StringBuilder("https://").append(webSite));
        } else {
            website.setText(webSite);
            checkSite(webSite, webName, webIntroduce, appUserId, appUserNickName, callback);
        }
        name.setText(webName);
        description.setText(webIntroduce);
        website.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                checkSite(website.getText().toString().trim(), webName, webIntroduce, appUserId, appUserNickName, callback);
            } else {
                name.setEnabled(true);
                description.setEnabled(true);
            }
        });
        confirm.setOnClickListener(v -> {
            if (!Patterns.WEB_URL.matcher(website.getText()).matches()) {
                Toast.makeText(activity, "非法网址", Toast.LENGTH_SHORT).show();
                return;
            }
            if (resultCallback != null) {
                if (dataBean[0] == null) {
                    resultCallback.onResult(website.getText().toString().trim(),
                            name.getText().toString().trim(),
                            description.getText().toString().trim());
                } else {
                    resultCallback.onResult(dataBean[0]);
                }

            }
            dialog.dismiss();
        });

        cancel.setOnClickListener(v -> dialog.dismiss());
        dialog.setOnDismissListener(DialogInterface::dismiss);
    }

    private static void checkSite(String webUrl, String webName, String webIntroduce, String appUserId, String appUserNickName, SimpleResultCallback simpleResultCallback) {
        Map<String, String> params = new HashMap<>();
        params.put("webName", webName);
        params.put("webUrl", webUrl);
        params.put("introduce", webIntroduce);
        params.put("uuid", Tools.getUniquePsuedoID());
        params.put("appUserId", appUserId);
        params.put("appUserNickName", appUserNickName);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.CHECK_SITE, params, new GsonObjectCallback<AddSiteBean>() {
            @Override
            public void onUi(AddSiteBean addSiteBean) {
                AddSiteBean.DataBean dataBean = addSiteBean.getData();
                simpleResultCallback.onBean(dataBean);
            }

            @Override
            public void onFailed(Call call, IOException e) {
                simpleResultCallback.onBean(null);
            }
        });
    }

    public static void addSortDialog(String text, Activity activity, SimpleResultCallback resultCallback) {
        Dialog dialog = new Dialog(activity, R.style.no_title);
        View view = View.inflate(activity, R.layout.dialog_add_sort, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
        lp.width = Tools.getScreenWidth(activity);
        dialogWindow.setAttributes(lp);
        EditText sortName = view.findViewById(R.id.sortName);
        TextView confirm = view.findViewById(R.id.confirm);
        if (!activity.isFinishing()) {
            dialog.show();
        }

        if (!TextUtils.isEmpty(text)) {
            sortName.setText(text);
        }

        confirm.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton(sortName.getText().toString().trim());
            }
        });
        dialog.setOnDismissListener(DialogInterface::dismiss);
    }

    public static void editSortDialog(Context context, WebInfoEntity webInfoEntity, List<SortInfoEntity> entities, SimpleResultCallback callback) {
        Dialog dialog = new Dialog(context, R.style.no_title);
        View view = View.inflate(context, R.layout.dialog_edit_sort, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
        lp.width = Tools.getScreenWidth(context);
        dialogWindow.setAttributes(lp);

        RecyclerView sortList = view.findViewById(R.id.sortList);
        EditSortAdapter adapter = new EditSortAdapter(entities);
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        sortList.setLayoutManager(manager);
        sortList.addItemDecoration(new CommonItemDecoration(Tools.dp2px(context, 10),
                Tools.dp2px(context, 10), Tools.dp2px(context, 10)));
        sortList.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view1, position) -> {
            webInfoEntity.sortName = entities.get(position).sortName;
            WebInfoDBUtils.insertWebInfo(context, webInfoEntity);
            if (callback != null) {
                callback.onResult(entities.get(position).sortName, "");
            }
            dialog.dismiss();
        });
        TextView cancel = view.findViewById(R.id.cancel);
        cancel.setOnClickListener(v -> dialog.dismiss());
        dialog.setOnDismissListener(DialogInterface::dismiss);
        dialog.show();
    }

    public static void updateUserInfo(Activity activity, String nickName, SimpleResultCallback resultCallback) {
        Dialog dialog = new Dialog(activity, R.style.no_title);
        View view = View.inflate(activity, R.layout.dialog_update_info, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = (int) (Tools.getScreenWidth(activity) * 0.85);
        dialogWindow.setAttributes(lp);

        EditText sortName = view.findViewById(R.id.sortName);
        TextView confirm = view.findViewById(R.id.confirm);
        if (!activity.isFinishing()) {
            dialog.show();
        }
        sortName.setText(nickName);
        confirm.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton(sortName.getText().toString().trim());
            }
        });
        dialog.setOnDismissListener(DialogInterface::dismiss);
    }

    public static void forceUpdate(String versionStr, String contentStr, Activity activity, SimpleResultCallback resultCallback) {
        Dialog dialog = new Dialog(activity, R.style.no_title);
        View view = View.inflate(activity, R.layout.dialog_force_update, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = (int) (Tools.getScreenWidth(activity) * 0.85);
        dialogWindow.setAttributes(lp);

        TextView content = view.findViewById(R.id.content);
        TextView version = view.findViewById(R.id.version);
        TextView confirm = view.findViewById(R.id.confirm);
        if (!activity.isFinishing()) {
            dialog.show();
        }

        version.setText(versionStr);
        content.setText(contentStr);
        confirm.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("confirm");
            }
        });
        dialog.setOnDismissListener(DialogInterface::dismiss);
    }

    public static void sort(Context context, View clickView, SimpleResultCallback resultCallback) {
        Dialog dialog = new Dialog(context, R.style.no_title);
        View view = View.inflate(context, R.layout.alert_view, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.gravity = Gravity.TOP | Gravity.START;
        int[] location = new int[2];
        clickView.getLocationInWindow(location);
        lp.x = location[0];
        lp.y = location[1];
        dialogWindow.setAttributes(lp);

        ImageView move = view.findViewById(R.id.move);
        ImageView delete = view.findViewById(R.id.delete);

        move.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("move");
            }
        });
        delete.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("delete");
            }
        });
        dialog.show();
    }

    public static void syncDialog(Context context, SimpleResultCallback resultCallback) {
        Dialog dialog = new Dialog(context, R.style.no_title);
        View view = View.inflate(context, R.layout.sync_view, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        lp.width = (int) (Tools.getScreenWidth(context) * 0.85);
        dialogWindow.setAttributes(lp);

        TextView sync = view.findViewById(R.id.sync);
        TextView exit = view.findViewById(R.id.exit);
        sync.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("sync");
            }
        });
        exit.setOnClickListener(v -> {
            dialog.dismiss();
            if (resultCallback != null) {
                resultCallback.onButton("exit");
            }
        });
        dialog.show();
        dialog.setOnDismissListener(DialogInterface::dismiss);
    }
}
